//
//  BBCMD.m
//  LinkMap
//
//  Created by aron on 2022/5/7.
//  Copyright © 2022 ND. All rights reserved.
//

#import "BBCMD.h"
#import <mach-o/fat.h>

@implementation BBCMD

// Execute command in console.
static NSData * bb_cmd(NSString *cmd) {
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    NSFileHandle *file = [pipe fileHandleForReading];  // Start task
    NSError *err = nil;
    BOOL res = [task launchAndReturnError:&err];
    if (!res) {
        NSLog(@"error=%@", err);
    }
    
    NSData *data = [file readDataToEndOfFile];    // Get execution results.
    return data;
}

static NSData * bb_cmd2(NSString *cmd, NSArray *args, void(^completion)(void)) {
//    NSTask *task = [[NSTask alloc] init];
//    [task setLaunchPath: cmd];
//    NSArray *arguments = @[arg];
//    [task setArguments: arguments];
//    NSPipe *pipe = [NSPipe pipe];
//    [task setStandardOutput: pipe];
//
//    NSFileHandle *file = [pipe fileHandleForReading];  // Start task
//    NSError *err = nil;
//    BOOL res = [task launchAndReturnError:&err];
//    if (!res) {
//        NSLog(@"error=%@", err);
//    }
//
//    NSData *data = [file readDataToEndOfFile];    // Get execution results.
//    return data;
    
    NSError *err = nil;
    [NSTask launchedTaskWithExecutableURL:[NSURL fileURLWithPath:cmd] arguments:args error:&err terminationHandler:^(NSTask * _Nonnull) {
        NSLog(@"===terminationHandler");
        if (completion) {
            completion();
        }
    }];
    if (err) {
        NSLog(@"error=%@", err);
    }
    return nil;
}

void getUnusedClasses(NSString *appPath, NSString *resultPath, void(^completion)(void)) {
//    bb_cmd([NSString stringWithFormat:@"bladess -unused %@ -o %@",appPath, resultPath]);
    NSMutableArray *args = [NSMutableArray new];
    [args addObject:@"-unused"];
    [args addObject:appPath];
    [args addObject:@"-o"];
    [args addObject:resultPath];
    bb_cmd2(@"/usr/local/bin/blades", args, ^{
        !completion ?: completion();
    });
}

@end
